/*
 ******************************************************************************
 * Parts of this code sample are licensed under Apache License, Version 2.0   *
 * Copyright (c) 2009, Android Open Handset Alliance. All rights reserved.    *
 *																			  *																			*
 * Except as noted, this code sample is offered under a modified BSD license. *
 * Copyright (C) 2010, Motorola Mobility, Inc. All rights reserved.           *
 * 																			  *
 * For more details, see MOTODEV_Studio_for_Android_LicenseNotices.pdf        * 
 * in your installation folder.                                               *
 ******************************************************************************
 */
package dk.lector.providers;

import java.util.HashMap;

import dk.lector.datasource.DBhelper;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class USERContentProvider extends ContentProvider {

	private DBhelper dbHelper;
	private static HashMap<String, String> USER_PROJECTION_MAP;
	private static final String TABLE_NAME = "user";
	private static final String AUTHORITY = "dk.lector.providers.USERContentProvider";

	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
			+ "/" + TABLE_NAME);
	public static final Uri _ID_FIELD_CONTENT_URI = Uri.parse("content://"
			+ AUTHORITY + "/" + TABLE_NAME.toLowerCase());
	public static final Uri USERNAME_FIELD_CONTENT_URI = Uri.parse("content://"
			+ AUTHORITY + "/" + TABLE_NAME.toLowerCase() + "/username");
	public static final Uri PASSWORD_FIELD_CONTENT_URI = Uri.parse("content://"
			+ AUTHORITY + "/" + TABLE_NAME.toLowerCase() + "/password");
	public static final Uri USERNAME_PLAIN_FIELD_CONTENT_URI = Uri
			.parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
					+ "/username_plain");
	public static final Uri EMAIL_FIELD_CONTENT_URI = Uri.parse("content://"
			+ AUTHORITY + "/" + TABLE_NAME.toLowerCase() + "/email");
	public static final Uri FULL_NAME_FIELD_CONTENT_URI = Uri
			.parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
					+ "/full_name");
	public static final Uri TIMESTAMP_FIELD_CONTENT_URI = Uri
			.parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
					+ "/timestamp");
	public static final Uri TIMESTAMP_ACTIVITY_FIELD_CONTENT_URI = Uri
			.parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
					+ "/timestamp_activity");
	
	
	public static final String DEFAULT_SORT_ORDER = "_id ASC";

	private static final UriMatcher URL_MATCHER;

	private static final int USER = 1;
	private static final int USER__ID = 2;
	private static final int USER_USERNAME = 3;
	private static final int USER_PASSWORD = 4;
	private static final int USER_USERNAME_PLAIN = 5;
	private static final int USER_EMAIL = 6;
	private static final int USER_FULL_NAME = 7;
	private static final int USER_TIMESTAMP = 8;
	private static final int USER_TIMESTAMP_ACTIVITY = 9;

	// Content values keys (using column names)
	public static final String _ID = "_id";
	public static final String USERNAME = "username";
	public static final String PASSWORD = "password";
	public static final String USERNAME_PLAIN = "username_plain";
	public static final String EMAIL = "email";
	public static final String FULL_NAME = "full_name";
	public static final String TIMESTAMP = "timestamp";
	public static final String TIMESTAMP_ACTIVITY = "timestamp_activity";
	public static final String[] PROJECTION = new String[]{_ID,USERNAME,PASSWORD,USERNAME_PLAIN,EMAIL,FULL_NAME,TIMESTAMP,TIMESTAMP_ACTIVITY};

	public boolean onCreate() {
		dbHelper = new DBhelper(getContext(), true);
		return (dbHelper == null) ? false : true;
	}

	public Cursor query(Uri url, String[] projection, String selection,
			String[] selectionArgs, String sort) {
		SQLiteDatabase mDB = dbHelper.getReadableDatabase();
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		switch (URL_MATCHER.match(url)) {
		case USER:
			qb.setTables(TABLE_NAME);
			qb.setProjectionMap(USER_PROJECTION_MAP);
			break;
		case USER__ID:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("_id=" + url.getPathSegments().get(1));
			break;
		case USER_USERNAME:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("username='" + url.getPathSegments().get(2) + "'");
			break;
		case USER_PASSWORD:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("password='" + url.getPathSegments().get(2) + "'");
			break;
		case USER_USERNAME_PLAIN:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("username_plain='" + url.getPathSegments().get(2)
					+ "'");
			break;
		case USER_EMAIL:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("email='" + url.getPathSegments().get(2) + "'");
			break;
		case USER_FULL_NAME:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("full_name='" + url.getPathSegments().get(2) + "'");
			break;
		case USER_TIMESTAMP:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("timestamp='" + url.getPathSegments().get(2) + "'");
			break;
		case USER_TIMESTAMP_ACTIVITY:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("timestamp_activity='"
					+ url.getPathSegments().get(2) + "'");
			break;

		default:
			throw new IllegalArgumentException("Unknown URL " + url);
		}
		String orderBy = "";
		if (TextUtils.isEmpty(sort)) {
			orderBy = DEFAULT_SORT_ORDER;
		} else {
			orderBy = sort;
		}
		Cursor c = qb.query(mDB, projection, selection, selectionArgs, null,
				null, orderBy);
		c.setNotificationUri(getContext().getContentResolver(), url);
		return c;
	}

	public String getType(Uri url) {
		switch (URL_MATCHER.match(url)) {
		case USER:
			return "vnd.android.cursor.dir/vnd.com.tsmobile.user";
		case USER__ID:
			return "vnd.android.cursor.item/vnd.com.tsmobile.user";
		case USER_USERNAME:
			return "vnd.android.cursor.item/vnd.com.tsmobile.user";
		case USER_PASSWORD:
			return "vnd.android.cursor.item/vnd.com.tsmobile.user";
		case USER_USERNAME_PLAIN:
			return "vnd.android.cursor.item/vnd.com.tsmobile.user";
		case USER_EMAIL:
			return "vnd.android.cursor.item/vnd.com.tsmobile.user";
		case USER_FULL_NAME:
			return "vnd.android.cursor.item/vnd.com.tsmobile.user";
		case USER_TIMESTAMP:
			return "vnd.android.cursor.item/vnd.com.tsmobile.user";
		case USER_TIMESTAMP_ACTIVITY:
			return "vnd.android.cursor.item/vnd.com.tsmobile.user";

		default:
			throw new IllegalArgumentException("Unknown URL " + url);
		}
	}

	public Uri insert(Uri url, ContentValues initialValues) {
		SQLiteDatabase mDB = dbHelper.getWritableDatabase();
		long rowID;
		ContentValues values;
		if (initialValues != null) {
			values = new ContentValues(initialValues);
		} else {
			values = new ContentValues();
		}
		if (URL_MATCHER.match(url) != USER) {
			throw new IllegalArgumentException("Unknown URL " + url);
		}

		rowID = mDB.insert("user", "user", values);
		if (rowID > 0) {
			Uri uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
			getContext().getContentResolver().notifyChange(uri, null);
			return uri;
		}
		throw new SQLException("Failed to insert row into " + url);
	}

	public int delete(Uri url, String where, String[] whereArgs) {
		SQLiteDatabase mDB = dbHelper.getWritableDatabase();
		int count;
		String segment = "";
		switch (URL_MATCHER.match(url)) {
		case USER:
			count = mDB.delete(TABLE_NAME, where, whereArgs);
			break;
		case USER__ID:
			segment = url.getPathSegments().get(1);
			count = mDB.delete(TABLE_NAME,
					"_id="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case USER_USERNAME:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.delete(TABLE_NAME,
					"username="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case USER_PASSWORD:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.delete(TABLE_NAME,
					"password="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case USER_USERNAME_PLAIN:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.delete(TABLE_NAME,
					"username_plain="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case USER_EMAIL:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.delete(TABLE_NAME,
					"email="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case USER_FULL_NAME:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.delete(TABLE_NAME,
					"full_name="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case USER_TIMESTAMP:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.delete(TABLE_NAME,
					"timestamp="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case USER_TIMESTAMP_ACTIVITY:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.delete(
					TABLE_NAME,
					"timestamp_activity="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;

		default:
			throw new IllegalArgumentException("Unknown URL " + url);
		}
		getContext().getContentResolver().notifyChange(url, null);
		return count;
	}

	public int update(Uri url, ContentValues values, String where,
			String[] whereArgs) {
		SQLiteDatabase mDB = dbHelper.getWritableDatabase();
		int count;
		String segment = "";
		switch (URL_MATCHER.match(url)) {
		case USER:
			count = mDB.update(TABLE_NAME, values, where, whereArgs);
			break;
		case USER__ID:
			segment = url.getPathSegments().get(1);
			count = mDB.update(TABLE_NAME, values,
					"_id="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case USER_USERNAME:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.update(TABLE_NAME, values,
					"username="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case USER_PASSWORD:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.update(TABLE_NAME, values,
					"password="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case USER_USERNAME_PLAIN:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.update(TABLE_NAME, values,
					"username_plain="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case USER_EMAIL:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.update(TABLE_NAME, values,
					"email="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case USER_FULL_NAME:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.update(TABLE_NAME, values,
					"full_name="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case USER_TIMESTAMP:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.update(TABLE_NAME, values,
					"timestamp="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case USER_TIMESTAMP_ACTIVITY:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.update(
					TABLE_NAME,
					values,
					"timestamp_activity="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;

		default:
			throw new IllegalArgumentException("Unknown URL " + url);
		}
		getContext().getContentResolver().notifyChange(url, null);
		return count;
	}

	static {
		URL_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase(), USER);
		URL_MATCHER
				.addURI(AUTHORITY, TABLE_NAME.toLowerCase() + "/#", USER__ID);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase() + "/username"
				+ "/*", USER_USERNAME);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase() + "/password"
				+ "/*", USER_PASSWORD);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase()
				+ "/username_plain" + "/*", USER_USERNAME_PLAIN);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase() + "/email"
				+ "/*", USER_EMAIL);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase() + "/full_name"
				+ "/*", USER_FULL_NAME);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase() + "/timestamp"
				+ "/*", USER_TIMESTAMP);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase()
				+ "/timestamp_activity" + "/*", USER_TIMESTAMP_ACTIVITY);

		USER_PROJECTION_MAP = new HashMap<String, String>();
		USER_PROJECTION_MAP.put(_ID, "_id");
		USER_PROJECTION_MAP.put(USERNAME, "username");
		USER_PROJECTION_MAP.put(PASSWORD, "password");
		USER_PROJECTION_MAP.put(USERNAME_PLAIN, "username_plain");
		USER_PROJECTION_MAP.put(EMAIL, "email");
		USER_PROJECTION_MAP.put(FULL_NAME, "full_name");
		USER_PROJECTION_MAP.put(TIMESTAMP, "timestamp");
		USER_PROJECTION_MAP.put(TIMESTAMP_ACTIVITY, "timestamp_activity");

	}
}
